<template>
  <j-modal
    :title="title"
    :maskClosable="true"
    :width="500"
    placement="right"
    :closable="true"
    @close="handleCancel"
    @cancel="handleCancel"
    :visible="visible"
    switchFullscreen
    style="height: 100%;overflow: auto;">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="用户账号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入用户账号" v-decorator.trim="[ 'userName', validatorRules.userName]"
                   :disabled="model.id"/>
        </a-form-item>
        <a-form-item v-if="!model.id" :labelCol="labelCol" :wrapperCol="wrapperCol" label="登录密码">
          <a-input-password v-decorator.trim="[ 'pw', validatorRules.pw]" placeholder="请输入登录密码" type="password"/>
        </a-form-item>
        <a-form-item label="确认密码" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="!model.id">
          <a-input-password type="password" placeholder="请输入确认密码"
                            v-decorator.trim="[ 'confirmpassword', validatorRules.confirmpassword]"/>
        </a-form-item>
        <a-form-item label="用户名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入用户名称" :disabled="disableSubmit"
                   v-decorator.trim="[ 'realName', validatorRules.realName]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="角色"
        >
          <j-select-role placeholder="角色" v-decorator="[ 'roleNames']" :giveBackList="model.roleList"
                         :returnName="true"
                         @select="handleRoleCode" :disabled="disableSubmit"/>
        </a-form-item>
        <a-form-item v-if="!itemShow" :labelCol="labelCol" :wrapperCol="wrapperCol" label="用户类型">
          <cn-dict-select-tag
            v-decorator="[ 'userType']"
            :disabled="disableSubmit"
            :options="{value:'dictDataCode',label:'dictDataDesc'}"
            dict-code="user_type"
            placeholder="请选择用户类型"
            triggerChange/>
        </a-form-item>
<!--        <a-form-item-->
<!--          :labelCol="labelCol"-->
<!--          :wrapperCol="wrapperCol"-->
<!--          label="组织"-->
<!--          v-if="!itemShow"-->
<!--        >-->
<!--          <a-tree-select-->
<!--            style="width:100%"-->
<!--            :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"-->
<!--            :treeData="treeData"-->
<!--            v-decorator="['departCode', validatorRules.select]"-->
<!--            placeholder="请选择组织"-->
<!--            show-search-->
<!--            tree-default-expand-all-->
<!--            tree-node-filter-prop="title"-->
<!--            :replaceFields="{children:'children', title:'orgName', key:'orgCode', value: 'orgCode' }"-->
<!--            @change="handleDepartCode"-->
<!--            :disabled="disableSubmit"-->
<!--          >-->
<!--          </a-tree-select>-->
<!--        </a-form-item>-->
<!--        <a-form-item label="上级用户" v-if="!itemShow" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--          <a-input-search placeholder="请选择上级" v-decorator="['parentRealName']" :disabled="disableSubmit"-->
<!--                          readOnly enter-button @search="productSearch('superiorUser')"/>-->
<!--          <a-input readOnly type="hidden" v-decorator="[ 'parentUserName', {}]"/>-->
<!--        </a-form-item>-->
<!--        <a-form-item label="OA账号" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="!itemShow">-->
<!--          <a-input placeholder="请输入OA账号" v-decorator.trim="['jobNum']" :disabled="disableSubmit"/>-->
<!--        </a-form-item>-->
        <a-form-item label="手机号码" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入手机号码" :disabled="disableSubmit"
                   v-decorator="['telephone', validatorRules.telephone]"

                   :maxLength="11"/>
        </a-form-item>
        <a-form-item label="用户状态" v-if="!itemShow" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <cn-dict-select-tag
            placeholder="请选择用户状态"
            dict-code="job_status"
            triggerChange
            :disabled="disableSubmit"
            @change="userchange"
            :options="{value:'dictDataCode',label:'dictDataDesc'}"
            v-decorator.trim="[ 'jobStatus']"/>
        </a-form-item>
        <a-form-item :label="this.showCode" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="itemShow">
          <j-select-cust v-decorator="['name', validatorRules.select]"
                         :giveBackList="model.customers"
                         selectButtonText="选择" :inputs="true"
                         searchIcon="search" :multiple="true"
                         :returnName="true"
                         rowKey="custCode"
                         listUrl="/customerController/getPageList"
                         :queryParams="{userName:form.getFieldValue('userName'),permflag: 'external_user_page_impl_add_cust'}"
                         :disabled="disableSubmit"
                         @select="activeSelect"/>
        </a-form-item>
      </a-form>
    </a-spin>
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSubmit" v-if="!disableSubmit">确认</a-button>
    </template>
    <proChose ref="prochoose" v-bind="modalProps" @okbro="okbropro"></proChose>
  </j-modal>
</template>

<script>
  import proChose from '@comp/cn-components/ProChose'
  import { pick } from 'lodash'
  import moment from 'moment'
  import Vue from 'vue'
  // 引入搜索部门弹出框的组件
  import departWindow from './DepartWindow'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { getAction } from '@/api/manage'
  import { addUser, editUser, queryUserRole, queryall, queryDepartTreeList } from '@/api/api'
  import { disabledAuthFilter } from '@/utils/authFilter'
  import { duplicateCheck } from '@/api/api'
  import JImageUpload from '@/components/cn-form/JImageUpload'
  import { isMobile } from '@/utils/validate'
  import CodeConfigModal from '@/components/cn-select-popup/CodeConfigModal'
  import JSelectRole from '@/components/cn-select-popup/JSelectRole'
  import JSelectCust from '@/components/cn-select-popup/CnSelectCust'

  export default {
    name: 'UserModal',
    components: {
      JImageUpload,
      departWindow,
      CodeConfigModal,
      proChose,
      JSelectRole,
      JSelectCust
    },
    data() {
      return {
        name: '',
        treeData: [],
        itemShow: false,
        custList: [],
        ismutiple: true,
        showCode: '关联门店',
        drawerWidth: 800,
        modalWidth: 800,
        modaltoggleFlag: true,
        confirmDirty: false,
        disableSubmit: false,
        dateFormat: 'YYYY-MM-DD',
        userTypeTp: '1',
        validatorRules: {
          userName: {
            rules: [{
              required: true, message: ''
            }]
          },
          userType: {
            rules: [{
              required: true, message: ''
            }]
          },
          pw: {
            rules: [{
              required: true,
              pattern: /^(?=.*[a-zA-Z])(?=.*\d).{7,}$/,
              message: ''
            }, {
              validator: this.validateToNextPassword
            }]
          },
          confirmpassword: {
            rules: [{
              required: true, message: ''
            }, {
              validator: this.compareToFirstPassword
            }]
          },
          realName: { rules: [{ required: true, message: '' }] },
          roleNames: { rules: [{ required: true, message: '' }] },
          // code: { rules: [{ required: true, message: '请选择门店或者经销商!' }] },
          telephone: { rules: [{ validator: this.validatePhone }] },
          email: { rules: [{ validator: this.validateEmail }] },
          select: {
            rules: [{
              required: true, message: ''
            }]
          }
          // jobNum: { rules: [{ required: true, message: '请输入工号!' }] }
        },
        title: '操作',
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        uploadLoading: false,
        confirmLoading: false,
        headers: {},
        form: this.$form.createForm(this),
        picUrl: '',
        url: {
          fileUpload: window._CONFIG['domianUploadURL'] + '/cnUploadController/uploadOss'
        },
        identity: '1',
        fileList: []
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }
      this.initTenantList()
    },
    computed: {
      uploadAction: function() {
        return this.url.fileUpload
      },
      modalProps() {
        return {
          name: this.name
        }
      }
    },
    methods: {
      okbropro(val, status, status2) {
        let objs = JSON.parse(JSON.stringify(val[0]))
        this.form.setFieldsValue({
          parentUserName: objs.userName,
          parentRealName: objs.realName
        })
      },
      productSearch(status) {
        this.$refs.prochoose.rowKey = 'id'
        let formconfig = [
          {
            key: 'userName',
            label: '用户账户'
          },
          {
            key: 'realName',
            label: '用户名称'
          }
        ]
        let tableconfig = {
          columns: [
            {
              title: '用户账户',
              align: 'left',
              dataIndex: 'userName',
              width: 120,
              ellipsis: true
            },
            {
              title: '用户名称',
              align: 'left',
              dataIndex: 'realName',
              width: 120,
              ellipsis: true
            }
          ],
          list: window._CONFIG['domianURL'] + '/cnUserController/getPageList',
          multiple: false,
          columW: 10
        }

        this.name = '用户'
        let dataSource = []
        if (this.form.getFieldValue('superiorUser')) {
          dataSource = [{
            userName: this.form.getFieldValue('superiorUser'),
            realName: this.form.getFieldValue('realsname')
          }]
        }
        console.log(dataSource)
        this.$refs.prochoose.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
      },
      isDisabledAuth(code) {
        return disabledAuthFilter(code)
      },
      initTenantList() {
        // getAction(this.url.queryTenantList).then(res=>{
        //   if(res.success){
        //     this.tenantList = res.result
        //   }
        // })
      },
      //窗口最大化切换
      toggleScreen() {
        if (this.modaltoggleFlag) {
          this.modalWidth = window.innerWidth
        } else {
          this.modalWidth = 800
        }
        this.modaltoggleFlag = !this.modaltoggleFlag
      },
      refresh() {
      },
      add() {
        this.edit({})
      },
      loadTree() {
        var that = this
        queryDepartTreeList({ permflag: 'user_page_impl_add_org' }).then((res) => {
          if (res.success) {
            that.treeData = []
            let treeList = res.result
            for (let a = 0; a < treeList.length; a++) {
              let temp = treeList[a]
              temp.isLeaf = temp.leaf
              that.treeData.push(temp)
            }
          }
        })
      },
      edit(record) {
        console.log(record.roleNames)
        // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
        this.resetScreenSize()
        let that = this
        that.checkedDepartNameString = ''
        that.form.resetFields()
        this.loadTree()
        if (record.hasOwnProperty('id')) {
          setTimeout(() => {
            this.fileList = [record.avatar]
          }, 5)
        }
        delete record.pw
        that.visible = true
        that.model = Object.assign({}, record)
        if (that.model.roleNames == undefined) {
          that.model.roleNames = ''
        } else {
          that.model.roleNames = that.model.roleNames + ''
        }
        that.model.roleList = that.returnList(that.model.roleNames, that.model.roleCodes + '', 'roleName', 'roleCode')
        this.userchange(that.model.userType)
        that.$nextTick(() => {
          if (this.model.id) {
            this.model.customers = this.model.customers || []
          }
          that.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
          if (record.custList && record.custList !== null) {
            this.showCode = '关联经销商'
            this.ismutiple = true
            this.custList = [{
              custCode: record.code,
              custName: record.name
            }]
          }
          that.model.custList = this.returnList(that.model.name, that.model.code, 'customerName', 'customerCode')
        })
      },

      // 数组
      returnList(names = '', codes = '', name = '', code = '') {
        let list = []
        if (names && codes) {
          names = names.split(',')
          codes = codes.split(',')
          for (let i = 0; i < names.length; i++) {
            list.push({
              [name]: names[i],
              [code]: codes[i]
            })
          }
        }
        return list
      },
      close() {
        this.$emit('close')
        this.visible = false
        this.fileList = []
      },
      moment,
      handleSubmit() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let formData = Object.assign(this.model, values)
            formData.roleNames = formData.roleNames.split(',')
            formData.custList = this.custList
            let obj
            if (!this.model.id) {
              formData.id = this.userId
              obj = addUser(formData)
            } else {
              obj = editUser(formData)
            }
            obj.then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.close()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
            })

          }
        })
      },
      handleCancel() {
        this.close()
      },
      validateToNextPassword(rule, value, callback) {
        const form = this.form
        const confirmpassword = form.getFieldValue('confirmpassword')
        if (value && confirmpassword && value !== confirmpassword) {
          callback('两次输入的密码不一样！')
        }
        if (value && this.confirmDirty) {
          form.validateFields(['confirm'], { force: true })
        }
        callback()
      },
      compareToFirstPassword(rule, value, callback) {
        const form = this.form
        if (value && value !== form.getFieldValue('pw')) {
          callback('两次输入的密码不一样！')
        } else {
          callback()
        }
      },
      validatePhone(rule, value, callback) {
        if (!value || new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
          callback()
        } else {
          callback('您的手机号码格式不正确!')
        }
        // if (!value) {
        //   callback()
        // } else {
        //   //update-begin--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
        //   if (new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
        //     //update-end--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
        //     var params = {
        //       tableName: 'sys_user',
        //       fieldName: 'phone',
        //       fieldVal: value,
        //       dataId: this.userId
        //     };
        //     duplicateCheck(params).then((res) => {
        //       if (res.success) {
        //         callback("手机号已存在!")
        //       } else {
        //
        //       }
        //     })
        //   } else {
        //     callback("请输入正确格式的手机号码!");
        //   }
        // }
      },
      validateEmail(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value)) {
            var params = {
              tableName: 'sys_user',
              fieldName: 'email',
              fieldVal: value,
              dataId: this.userId
            }
            callback()
            // duplicateCheck(params).then((res) => {
            //   console.log(res)
            //   if (res.success) {
            //     callback()
            //   } else {
            //     callback('邮箱已存在!')
            //   }
            // })
          } else {
            callback('请输入正确格式的邮箱!')
          }
        }
      },
      validateUsername(rule, value, callback) {
        let params = {
          tableName: 'sys_user',
          fieldName: 'userName',
          fieldVal: value,
          dataId: this.userId
        }
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback('用户名已存在!')
          }
        })
      },
      validateWorkNo(rule, value, callback) {
        var params = {
          tableName: 'sys_user',
          fieldName: 'work_no',
          fieldVal: value,
          dataId: this.userId
        }
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback('工号已存在!')
          }
        })
      },
      handleConfirmBlur(e) {
        const value = e.target.value
        this.confirmDirty = this.confirmDirty || !!value
      },

      // 搜索用户对应的部门API
      onSearch() {
        this.$refs.departWindow.add(this.checkedDepartKeys, this.userId)
      },

      // 获取用户对应部门弹出框提交给返回的数据
      modalFormOk(formData) {
        this.checkedDepartNames = []
        this.selectedDepartKeys = []
        this.checkedDepartNameString = ''
        this.userId = formData.userId
        this.userDepartModel.userId = formData.userId
        this.departIds = []
        this.resultDepartOptions = []
        var depart = []
        for (let i = 0; i < formData.departIdList.length; i++) {
          this.selectedDepartKeys.push(formData.departIdList[i].key)
          this.checkedDepartNames.push(formData.departIdList[i].title)
          this.checkedDepartNameString = this.checkedDepartNames.join(',')
          //新增部门选择，如果上面部门选择后不为空直接付给负责部门
          depart.push({
            key: formData.departIdList[i].key,
            title: formData.departIdList[i].title
          })
          this.departIds.push(formData.departIdList[i].key)
        }
        this.resultDepartOptions = depart
        this.userDepartModel.departIdList = this.selectedDepartKeys
        this.checkedDepartKeys = this.selectedDepartKeys  //更新当前的选择keys
      },
      // 根据屏幕变化,设置抽屉尺寸
      resetScreenSize() {
        let screenWidth = document.body.clientWidth
        if (screenWidth < 500) {
          this.drawerWidth = screenWidth
        } else {
          this.drawerWidth = 700
        }
      },
      identityChange(e) {
        if (e.target.value === '1') {
          this.departIdShow = false
        } else {
          this.departIdShow = true
        }
      },
      userchange(type) {
        this.userTypeTp = type
        this.custList = []
        if (type == 2) {
          this.itemShow = true
          this.showCode = '关联经销商'
          this.ismutiple = true
        } else if (type == 4) {
          this.itemShow = true
          this.showCode = '关联门店'
          this.ismutiple = true
        } else {
          this.showCode = ''
          this.ismutiple = true
          this.itemShow = false
        }
      },
      handleSelectCode() {
        this.$refs.CodeConfigModal.showModal(this.userTypeTp)
      },
      // handelSaveOk(ob, rowkeys) {
      //   let that = this
      //   if (ob != null && ob != null && this.showCode !== '关联经销商') {
      //     that.model.code = ob.code
      //     that.model.name = ob.name
      //     that.$nextTick(() => {
      //       that.form.setFieldsValue(pick(that.model, Object.keys(that.model)))
      //     })
      //   } else {
      //     this.custList = rowkeys.map(item => {
      //       return {
      //         custCode: item.code,
      //         custName: item.name
      //       }
      //     })
      //   }
      // },
      handleRoleCode(list) {
        if (list.length) {
          this.model.roleCodes = list.map(item => item.roleCode)
        }
        this.model.roleList = list
      },
      handleDepartCode(value, name) {
        console.log(name)
        this.model.departName = name.join()
      },
      activeSelect(v, k, y) {
        console.log(v, k, y)
        let that = this
        // this.model.custList = v
        // that.model.code = v[0].customerCode
        // that.model.name = v[0].customerName
        that.model.customers = v
      }
    }
  }

</script>

<style scoped>
  .avatar-uploader > .ant-upload {
    width: 104px;
    height: 104px;
  }

  .ant-upload-select-picture-card i {
    font-size: 49px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

  .ant-table-tbody .ant-table-row td {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  .drawer-bootom-button {
    position: absolute;
    bottom: -8px;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }
</style>

